package com.example.hm_dtfkz.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.android.base.util.http.RxhttpUtil;
import com.dq.ad.utils.ToastUtil;
import com.example.hm_dtfkz.MainActivity;
import com.example.hm_dtfkz.config.LoginConfig;
import com.example.hm_dtfkz.databinding.ActivityLoginBinding;
import com.example.hm_dtfkz.litepal.WXLogin;
import com.example.hm_dtfkz.ui.base.VBBaseActivity;
import com.example.hm_dtfkz.util.DQLog;
import com.example.hm_dtfkz.util.LoginLoadingUtil;
import com.google.gson.Gson;
import com.wx.login.WXLoginBroadcast;
import com.wx.login.WXUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * FileName: LoginActivity
 * Author: admin
 * Date: 2021/11/5 15:19
 * Description:
 */
@Route(path = "/main/Loginactivity")
public class RegistActivity extends VBBaseActivity {

    private ActivityLoginBinding loginBinding;

    private static final String KEY_LOGIN_TYPE = "key_login_type";
    public static final int TYPE_LOGIN = 1;
    public static final int TYPE_BIND = 2;

    private WXLoginBroadcast wxLoginBroadcast = null;
    private boolean isAgreement = false;

    public static LoginCallBack loginCallBack = null;
    private int type = TYPE_LOGIN;

    public static void startAct(Activity act, LoginCallBack callBack) {
        startAct(act, TYPE_LOGIN, callBack);
    }

    public static void startAct(Activity act, int type, LoginCallBack callBack) {
        Intent intent = new Intent(act, RegistActivity.class);
        intent.putExtra(KEY_LOGIN_TYPE, type);
        act.startActivity(intent);
        loginCallBack = callBack;
    }

    @Override
    protected ViewBinding getViewBinding() {
        setTitleBackground(BG_WHITE);
        return loginBinding = ActivityLoginBinding.inflate(getLayoutInflater());
    }

    @Override
    public void initView() {
        super.initView();
        if (!TextUtils.isEmpty(LoginConfig.getUserOpenId())) {
            startActivity(new Intent(RegistActivity.this, MainActivity.class));
            finish();
        }
        SpannableStringBuilder style = new SpannableStringBuilder();
        style.append("我已阅读并同意《用户协议》和《隐私政策》");
        ClickableSpan clickablePolicy = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                UserServiceAgreementActivity.startAct(RegistActivity.this, UserServiceAgreementActivity.TYPE_PRIVACY);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        };
        ClickableSpan clickableUser = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                UserServiceAgreementActivity.startAct(RegistActivity.this, UserServiceAgreementActivity.TYPE_USER);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        };
        style.setSpan(clickableUser, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(clickablePolicy, 14, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        loginBinding.tvAgreement.setText(style);

        //设置部分文字颜色
        ForegroundColorSpan foregroundPolicy =
                new ForegroundColorSpan(Color.parseColor("#FFEE32"));
        ForegroundColorSpan foregroundUser =
                new ForegroundColorSpan(Color.parseColor("#FFEE32"));
        style.setSpan(foregroundPolicy, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(foregroundUser, 14, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        //配置给TextView
        loginBinding.tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        loginBinding.tvAgreement.setText(style);
    }

    @Override
    public void initData() {
        super.initData();
        type = getIntent().getIntExtra(KEY_LOGIN_TYPE, TYPE_LOGIN);

        registerReceiver();

        WXUtils.initWxApi(getApplicationContext(), LoginConfig.APP_ID_WX);
        DQLog.e("WX_APPID:" + LoginConfig.APP_ID_WX);

        loginBinding.radioAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgreement = isChecked;
            }
        });

        loginBinding.ivLoginWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String model = Build.MODEL;
                DQLog.e("手机型号：" + model);
                if (model.contains("MI 8")) {
                    ToastUtil.showShortToast(RegistActivity.this, "设备异常，登录失败");
                    return;
                }
                if (model.contains("MI 9")) {
                    ToastUtil.showShortToast(RegistActivity.this, "设备异常，登录失败");
                    return;
                }

                if (!isAgreement) {
                    ToastUtil.showShortToast(RegistActivity.this, "请先勾选同意下方协议政策");
                    return;
                }
                Map<String,String>  map=new HashMap<>();
                map.put("username","zhangsan2");
                map.put("password","123456");
                RxhttpUtil.getInstance().post(RxhttpUtil.baseUrl + "/service/user/register", map, RegistActivity.this, new RxhttpUtil.RxHttpCallBack() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(String response) {
                        DQLog.e("RxhttpUtil==200" + response);

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String data = jsonObject.getString("data");
                            WXLogin qaIncomeResp = new Gson().fromJson(data, WXLogin.class);
                            LoginConfig.setLoginState(true);
                            LoginConfig.setUserOpenId(qaIncomeResp.getOpenid());
                            LoginConfig.setUserId(qaIncomeResp.getUnionid());
                            LoginConfig.setUserNickName(qaIncomeResp.getNickname());
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        LoginConfig.setUserOpenId("zhangsan");
                        finish();
                        startActivity(new Intent(RegistActivity.this, MainActivity.class));

                    }

                    @Override
                    public void onError(String error) {
                        DQLog.e("RxhttpUtil==error" + error);
                        startActivity(new Intent(RegistActivity.this, MainActivity.class));
                        finish();

                    }

                    @Override
                    public void onFinish() {

                    }
                });

            }
        });
    }

    private void registerReceiver() {
        wxLoginBroadcast = new WXLoginBroadcast(new WXLoginBroadcast.BroadcastCallback() {
            @Override
            public void onSuccess(@Nullable String code) {
                DQLog.e("微信登录成功:" + code);
                Log.e(TAG, "微信登录操作.....2 : " + code);
                LoginLoadingUtil.showLoading(RegistActivity.this, "登录中...");
                LoginConfig.setUserOpenId(code);
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "微信登录操作.....3 : " + type);
                        if (type == TYPE_LOGIN) {
                            if (loginCallBack != null) {
                                loginCallBack.onLogin(code);
                            }
                            RegistActivity.this.finish();
                        } else {
                            bindWx(code);
                        }
                    }
                });
                RegistActivity.this.finish();
            }

            @Override
            public void onFailed() {
                ToastUtil.showShortToastCenter(RegistActivity.this, "您已取消或拒绝登录");
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(getPackageName() + WXLoginBroadcast.BROADCAST_ACTION_SUCCESS);
        intentFilter.addAction(getPackageName() + WXLoginBroadcast.BROADCAST_ACTION_FAILED);
        registerReceiver(wxLoginBroadcast, intentFilter);
    }

    private void bindWx(String code) {
        ToastUtil.showShortToast(this,code);
//        HXCurrencySDK.getInstance().bind(2, "", code, "", 0, new HttpUtil.HttpUtilCallback() {
//            @Override
//            public void onSuccess(int reqCode, String response) {
//                DQLog.e("绑定微信成功：" + response);
//                BindResp bindResp = JsonUtil.parseObject(response, BindResp.class);
//                if (bindResp != null) {
//                    int errorCode = bindResp.getErrorCode();
//                    String errorMessage = bindResp.getErrorMessage();
//                    if (errorCode == 0) {
//                        String openId = bindResp.getOi();
//                        String hiu = bindResp.getHiu();
//
//                        LoginConfig.setUserOpenId(openId);
//                        LoginConfig.setUserHeadUrl(hiu);
//                        LoginConfig.setLoginState(true);
//                        ToastUtil.showShortToast(LoginActivity.this, "绑定微信成功");
//                    } else if (errorCode == 1009) {
//                        ToastUtil.showShortToast(LoginActivity.this, errorMessage + "，请退出应用后重新登录");
//                    } else {
//                        ToastUtil.showShortToast(LoginActivity.this, errorMessage);
//                    }
//                } else {
//                    ToastUtil.showShortToast(LoginActivity.this, "绑定微信失败");
//                }
//                LoginActivity.this.finish();
//            }
//
//            @Override
//            public void onFailed(int reqCode, Throwable throwable) {
//                DQLog.e("绑定微信失败：" + throwable.getMessage());
//                ToastUtil.showShortToast(LoginActivity.this, "绑定微信失败：" + throwable.getMessage());
//                LoginActivity.this.finish();
//            }
//        });
    }

    private void unregisterReceiver() {
//        if (wxLoginBroadcast != null) {
//            unregisterReceiver(wxLoginBroadcast);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoginLoadingUtil.dismissLoading();
        unregisterReceiver();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public interface LoginCallBack {
        void onLogin(String wxCode);
    }
}